<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { inventoryApi } from '../../services/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'

// 库存数据
const inventoryItems = ref([])
const loading = ref(false)
const total = ref(0)

// 分类选项
const categories = [
  { value: 'food', label: '食品' },
  { value: 'supplies', label: '用品' }
]

// 表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('添加库存')
const formRef = ref(null)
const formItem = ref({
  id: null,
  name: '',
  category: 'food',
  price: '',
  quantity: '',
  unit: '',
  description: ''
})
const isEditing = ref(false)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur', transform: value => Number(value) }
  ],
  quantity: [
    { required: true, message: '请输入库存量', trigger: 'blur' },
    { type: 'number', message: '库存量必须为数字', trigger: 'blur', transform: value => Number(value) }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ]
}

// 搜索和筛选
const searchQuery = ref('')
const categoryFilter = ref('all')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 监听搜索和筛选条件变化，重新加载数据
watch([searchQuery, categoryFilter], () => {
  currentPage.value = 1 // 重置到第一页
  fetchInventory()
})

// 获取所有库存
const fetchInventory = async () => {
  loading.value = true
  
  try {
    // 构建请求参数
    const params = {
      pageNum: currentPage.value - 1, // 后端从0开始计数
      pageSize: pageSize.value,
      inventory: {
        name: searchQuery.value === '' ? null : searchQuery.value,
        category: categoryFilter.value === 'all' ? null : categoryFilter.value
      }
    }
    
    // 如果选择了特定类别，添加到请求参数
    if (categoryFilter.value !== 'all') {
      params.inventory.category = categoryFilter.value === 'food' ? '食品' : '用品'
    }
    
    const response = await inventoryApi.getInventory(params)
    
    // 检查响应状态
    if (response.data.code === 200) {
      // 提取数据
      const { records, total: totalCount } = response.data.data
      console.log(response.data.data)
      inventoryItems.value = records || []
      total.value = totalCount || 0
    } else {
      ElMessage.error(response.data.message || '获取库存数据失败')
    }
  } catch (err) {
    console.error('获取库存失败:', err)
    ElMessage.error('获取库存数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchInventory()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  fetchInventory()
}

// 添加库存项
const addInventoryItem = async () => {
  try {
    await inventoryApi.addInventoryItem(formItem.value)
    ElMessage.success('添加成功')
    resetForm()
    dialogVisible.value = false
    fetchInventory()
  } catch (err) {
    console.error('添加库存失败:', err)
    ElMessage.error('添加库存失败，请稍后再试')
  }
}

// 更新库存项
const updateInventoryItem = async () => {
  try {
    await inventoryApi.updateInventoryItem(formItem.value.id, formItem.value)
    ElMessage.success('更新成功')
    resetForm()
    dialogVisible.value = false
    fetchInventory()
  } catch (err) {
    console.error('更新库存失败:', err)
    ElMessage.error('更新库存失败，请稍后再试')
  }
}

// 删除库存项
const deleteInventoryItem = async (id) => {
  ElMessageBox.confirm(
    '确定要删除这个库存项吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await inventoryApi.deleteInventoryItem(id)
      ElMessage.success('删除成功')
      fetchInventory()
    } catch (err) {
      console.error('删除库存失败:', err)
      ElMessage.error('删除库存失败，请稍后再试')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 打开编辑表单
const openEditForm = (item) => {
  formItem.value = { ...item }
  dialogTitle.value = '编辑库存'
  isEditing.value = true
  dialogVisible.value = true
}

// 打开添加表单
const openAddForm = () => {
  resetForm()
  dialogTitle.value = '添加库存'
  isEditing.value = false
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formItem.value = {
    id: null,
    name: '',
    category: 'food',
    price: '',
    quantity: '',
    unit: '',
    description: ''
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) 
  
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if (isEditing.value) {
        updateInventoryItem()
      } else {
        addInventoryItem()
      }
    } else {
      console.log('表单验证失败', fields)
    }
  })
}

// 获取类别名称
const getCategoryLabel = (value) => {
  if (value === '食品') return '食品'
  if (value === '用品') return '用品'
  
  const category = categories.find(cat => cat.value === value)
  return category ? category.label : value
}

// 获取类别类型
const getCategoryType = (value) => {
  if (value === '食品') return 'success'
  if (value === '用品') return 'info'
  return value === 'food' ? 'success' : 'info'
}

// 页面加载时获取库存数据
onMounted(() => {
  fetchInventory()
})
</script>

<template>
  <div class="inventory-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>库存管理</h2>
          <div class="header-actions">
            <el-button type="primary" :icon="Refresh" circle @click="fetchInventory" title="刷新" />
            <el-button type="success" :icon="Plus" @click="openAddForm">添加库存</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索库存名称..."
          class="search-input"
          :prefix-icon="Search"
          clearable
          @keyup.enter="fetchInventory"
        />
        
        <el-select v-model="categoryFilter" placeholder="类别" class="category-filter">
          <el-option label="所有类别" value="all" />
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-button type="primary" @click="fetchInventory">查询</el-button>
      </div>
      
      <!-- 库存表格 -->
      <el-table
        :data="inventoryItems"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="类别" min-width="100">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" min-width="100">
          <template #default="scope">
            {{ scope.row.price }} ¥
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存量" min-width="100" />
        <el-table-column prop="unit" label="单位" min-width="80" />
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">
            {{ scope.row.createTime ? new Date(scope.row.createTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              :icon="Edit"
              circle
              size="small"
              @click="openEditForm(scope.row)"
            />
            <el-button
              type="danger"
              :icon="Delete"
              circle
              size="small"  
              @click="deleteInventoryItem(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
          size="small"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
      
      <!-- 空数据提示 -->
      <el-empty v-if="!loading && inventoryItems.length === 0" description="暂无库存数据" />
    </el-card>
    
    <!-- 添加/编辑表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formItem"
        :rules="rules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formItem.name" placeholder="请输入名称" />
        </el-form-item>
        
        <el-form-item label="类别" prop="category">
          <el-select v-model="formItem.category" placeholder="请选择类别" style="width: 100%">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formItem.price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="库存量" prop="quantity">
          <el-input-number
            v-model="formItem.quantity"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formItem.unit" placeholder="请输入单位" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formItem.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.inventory-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.category-filter {
  width: 150px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 